package com.zl.shirodemo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.zl.shirodemo.config.PlatFormContext;
import com.zl.shirodemo.config.UserNamePasswordToken;
import com.zl.shirodemo.entity.SysUser;
import com.zl.shirodemo.requestBean.LoginBean;
import com.zl.shirodemo.util.JWTUtil;

@Controller
public class LoginController {
    @Autowired
    private JWTUtil jwtUtil;
    
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody LoginBean loginBean) {
        UserNamePasswordToken usernamePasswordToken = new UserNamePasswordToken(loginBean.getUserName(), loginBean.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(usernamePasswordToken);
        SysUser sysUser = PlatFormContext.currentUser.get();
        
        //使用用户自己的密码作为token签名的密钥，减少因密钥泄露造成大面积的问题
        String token = jwtUtil.getToken(sysUser.getUserid(), sysUser.getPassowrd());
        return ResponseEntity.ok(token);
    }
    
    @PostMapping("/logout")
    public ResponseEntity logout() {
        SecurityUtils.getSubject().logout();
        return ResponseEntity.ok().build();
    }
    
    
}
